package com.example.clothingmanager.service;

import com.example.clothingmanager.bean.Depot;
import com.example.clothingmanager.bean.User;
import com.example.clothingmanager.dao.UserDao;
import com.example.clothingmanager.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.List;
import java.util.Optional;

/**
 * @author Huangyt
 * @version 1.0
 * @date 2020/5/9 23:43
 */
@Service
public class UserService {
    @Autowired
    UserDao userDao;

    public Result list(int page, int size, HttpSession session){
        if(page<1){
            page = 1;
        }
        page -= 1;
        Sort.Order order = new Sort.Order(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        String account = (String) session.getAttribute("user");
        Page<User> users = userDao.findAll(account, pageable);
        return Result.success(users);
    }

    public Result add(User user){
        User byAccount = userDao.findByAccount(user.getAccount());
        if(null==byAccount){
            User data_user = userDao.saveAndFlush(user);
            return Result.success(data_user);
        }
        return Result.fail("账号已存在，添加失败");
    }

    public Result get(int id){
        Optional<User> optional = userDao.findById(id);
        if(optional.isPresent()){
            return Result.success(optional.get());
        }
        return Result.fail("用户ID不存在，获取失败");
    }

    public Result update(User user){
        Optional<User> optional = userDao.findById(user.getId());
        if(optional.isPresent()){
            return Result.success(userDao.saveAndFlush(user));
        }
        return Result.fail("用户ID不存在,更新失败");
    }

    public Result delete(int id){
        Optional<User> optional = userDao.findById(id);
        if(optional.isPresent()){
            userDao.deleteById(id);
            return Result.success();
        }
        return Result.fail("用户ID不存在,删除失败");
    }

    public Result list(){
        List<User> list = userDao.findAll();
        if(list.size()>0){
            return Result.success(list);
        }
        return Result.fail("用户列表为空");
    }
}
